package com.qingshu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qingshu.common.entity.custom.Music;
import com.qingshu.common.entity.custom.model.MusicAddModel;
import com.qingshu.common.entity.custom.model.MusicQueryModel;
import com.qingshu.common.entity.custom.model.MusicResourceModel;
import com.qingshu.common.entity.custom.vo.MusicTypeStatistics;
import com.qingshu.common.entity.custom.vo.MusicVO;
import com.qingshu.common.util.model.FieldUtil;
import com.qingshu.common.util.model.ModelUtil;
import com.qingshu.common.util.string.StringUtils;
import com.qingshu.mapper.MusicMapper;
import com.qingshu.mapper.MusicTypeMapper;
import com.qingshu.service.IFileService;
import com.qingshu.service.IMusicService;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author Huzz
 * @since 2021-12-09
 */
@Service
public class MusicServiceImpl extends ServiceImpl<MusicMapper, Music> implements IMusicService {

    @Autowired
    private IFileService fileService;

    @Autowired
    private MusicTypeMapper musicTypeMapper;

    @Override
    public boolean addMusic(MusicAddModel model) {
        // TODO 如果albumName不为空, 需要新建该专辑
        Music music = (Music) ModelUtil.toEntityStatic(model, Music.class);
        // 设置创建信息, 默认信息默认也是更新信息
        FieldUtil.setCreatedAndUpdateField(music);

        return this.baseMapper.insert(music) > 0;
    }

    @Transactional
    @Override
    public boolean addMusicByList(List<MusicAddModel> modelList) {
        for (MusicAddModel model : modelList) {
            // TODO 如果albumName不为空, 需要新建该专辑
            Music music = (Music) ModelUtil.toEntityStatic(model, Music.class);
            // 设置创建信息, 默认信息默认也是更新信息
            FieldUtil.setCreatedAndUpdateField(music);
            baseMapper.insert(music);
        }
        return true;
    }

    @Override
    public boolean updateMusicById(Music music) {
        // 设置更新信息
        FieldUtil.setUpdateField(music);

        return this.baseMapper.updateById(music) > 0;
    }

    @Override
    public boolean delMusicById(Integer musicId) {
        return this.baseMapper.deleteById(musicId) > 0;
    }

    @Override
    public Page<MusicVO> findMusicPage(Integer pageNum, Integer pageSize, MusicQueryModel model) {
        QueryWrapper<Music> wrapper = new QueryWrapper<>();
        if (model.getId() != null) {
            wrapper.lambda().eq(Music::getId, model.getId());
        }
        if (StringUtils.isNotEmpty(model.getMusicName())) {
            wrapper.lambda().like(Music::getMusicName, model.getMusicName());
        }
        if (StringUtils.isNotNull(model.getSingerName())) {
            wrapper.like("singer.singer_name", model.getSingerName());
        }

        return this.baseMapper.selectMusicPage(new Page<>(pageNum, pageSize), wrapper);
    }

    @Override
    public Music finMusicById(Integer musicId) {
        return this.baseMapper.selectById(musicId);
    }

    @Override
    public Music finUserByRoleName(String musicName) {
        LambdaQueryWrapper<Music> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Music::getMusicName, musicName);

        return this.baseMapper.selectOne(wrapper);
    }

    @Override
    public Map<String, String> getMusicResource(MusicResourceModel model) {
        Map<String, String> resultMap = new HashMap<>();
        if (model.getMusicFileId() != null) {
            resultMap.put("MUSIC", fileService.getFilePath(model.getMusicFileId()));
        }
        if (model.getLyricFileId() != null) {
            resultMap.put("LYRIC", fileService.getFilePath(model.getLyricFileId()));
        }
        if (model.getSingerAvatarFileId() != null) {
            resultMap.put("SINGER_AVATAR", fileService.getFilePath(model.getSingerAvatarFileId()));
        }
        return resultMap;
    }

    @Override
    public List<Map<String, Object>> getMusicTypePercentage() {
        List<Map<String, Object>> resultList = new ArrayList<>();
        // 非空类型排序
        List<MusicTypeStatistics> musicTypeNotNull = this.baseMapper.getMusicTypePercentage();
        // 空类型
        Integer musicTypeNull = this.baseMapper.getMusicTypeIsNullPercentage();
        // 歌曲总数
        Integer total = this.baseMapper.getTotal();

        // "其它" 的值
        int val = 0;
        for (int i = 0; i < musicTypeNotNull.size(); i++) {
            MusicTypeStatistics next = musicTypeNotNull.get(i);
            // 界面需求是最多展示5个类型, 多余的合并成"其它"
            if (i < 4) {
                // 遍历不超过4次或者集合size不超过5时
                Map<String, Object> item = new HashMap<>();
                item.put("name", next.getName());
                item.put("percentage", String.format("%.2f", (double) next.getCount() / total * 100));
                resultList.add(item);
            } else {
                // 第5次遍历开始, 将所有值相加起来
                val += next.getCount();
            }
        }

        int otherCount = val + musicTypeNull;

        if (otherCount != 0) {
            Map<String, Object> item = new HashMap<>();
            item.put("name", "其它");
            item.put("percentage", String.format("%.2f", (double) (otherCount / total * 100)));
            resultList.add(item);
        }

        return resultList;
    }
}
